<template>
  <div class="Message-form">
    <h2>留言板</h2>

    <!-- 留言输入表单 -->
    <div>
      <label for="message">输入留言：</label>
      <textarea
        id="message"
        v-model="message"
        @input="calculateRemainingCharacters"
        placeholder="请输入留言..."
        ref="messageInput"
      ></textarea>
      <p>剩余字符：{{ remainingCharacters }}</p>
      <button @click="submitMessage">提交留言</button>
      <p> </p>
    </div>

    <!-- 留言列表 -->
    <ul>
      <!-- 留言条目 -->
      <li v-for="(msg, index) in messages" :key="index">
        <MessageItem
          :message="msg"
          @delete-message="deleteMessage(index)"
        >
          <!-- 自定义留言显示的插槽 -->
          <template v-slot:default="{ msg }">
            <span>{{ msg }}</span>
          </template>
        </MessageItem>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import MessageItem from './MessageItem.vue';

const message = ref('');
const messages = ref([]);
const remainingCharacters = ref(100);

function calculateRemainingCharacters() {
  remainingCharacters.value = 100 - message.value.length;
}

function submitMessage() {
  if (message.value.trim() !== '') {
    messages.value.push(message.value);
    message.value = '';
    remainingCharacters.value = 100;
  }
}

function deleteMessage(index) {
  messages.value.splice(index, 1);
}
</script>

<style scoped>
/* 父组件 MessageBoard 样式 */
div {
  margin-bottom: 20px;
  margin-left: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
}

textarea {
  width: 100%;
  height: 100px;
  padding: 8px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: none;
}

.Message-form-button {
  background-color: #28a745;
  color: white;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}

.Message-form button:hover {
  background-color: #218838;
}

p {
  margin-top: 0;
  font-size: 0.9em;
  color: #888;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f9f9f9;
}
</style>